<?php

namespace app\airobot\controller;

use app\airobot\CommonLogic;
use app\airobot\model\ConfigFileOnline;
use app\airobot\model\ConfigFileTmp;
use app\airobot\model\Product;
use think\admin\Controller;
use think\facade\Db;
use think\facade\Log;

/**
 * 超管系统-配置上传
 * Class ConfigFileUpload
 * @package app\airobot\controller
 */
class ConfigFileUpload extends Controller
{
    private $table = 'config_file_tmp';
    public $commonLogic;

    /**
     * 配置上传
     * @auth true
     */
    public function index()
    {
        $this->commonLogic = new CommonLogic();
        $this->title = '配置上传';
        $query = $this->_query($this->table);
        $where = [];
        $query->where($where);
        $query->order('id asc')->page();
    }

    protected function _index_page_filter(array &$data)
    {
        /*foreach ($data as &$vo) {

        }*/
    }

    public function import()
    {
        // 保存
        try {
            $adminInfo = $this->app->session->get("user");
            $file = $this->app->request->post('file');
            if (!$file) $this->error('文件不能为空');
            $file = '.' . str_replace("https://box-static.airobot.fund", '', $file);

            // 文件名
            $fileArr = explode("/", $file);
            $fileNameArr = explode("-", $fileArr[count($fileArr) - 1]);
            $fileName = $fileNameArr[count($fileNameArr) - 1];
            if (!in_array($fileName, ['box_rtp.csv', 'forge_rtp.csv', 'box.csv', 'forge.csv', 'product.csv',])) {
                $this->error("文件名不对！");
            }

            // 已经存在同名文件
            $configFileTmpList = Db::table('config_file_tmp')->where(['config_name' => $fileName])->select()->toArray();
            if (count($configFileTmpList) > 0) {
                $this->error("已存在相同配置！");
            }

            // 创建
            $createData = [];
            $createData["manager_id"] = $adminInfo['id'];
            $createData["manager_name"] = $adminInfo['username'];
            $createData["config_name"] = $fileName;
            $createData["config_file"] = $file;
            $configFileTmp = new ConfigFileTmp();
            $configFileTmp->createInfo($createData);
        } catch (\Exception $e) {
            $this->error("上传失败");
        }

        $this->success('上传成功');
    }

    /**
     * 单个比较
     * @auth true
     */
    public function diff()
    {
        $params = $this->request->post();
        $configFileTmpModel = new ConfigFileTmp();
        $configTmpInfo = $configFileTmpModel->queryInfo(['id' => $params['id']]);
        $file2 = $configTmpInfo['config_file'];

        $configFileOnlineModel = new ConfigFileOnline();
        $configOnlineInfo = $configFileOnlineModel->queryInfo(['config_name' => $configTmpInfo['config_name']]);
        $file1 = $configOnlineInfo['config_file'];

        // 使用 shell_exec 执行 diff 命令生成差异
        $diffOutput = shell_exec("git diff --no-index $file1 $file2");
        if (is_null($diffOutput)) {
            $this->error('没有变化!');
        }
        $this->success('比较成功', $diffOutput);
    }

    /**
     * 批量发布
     * @auth true
     */
    public function release()
    {
        try {
            // 开启事务
            Db::startTrans();
            $params = $this->request->post();

            // 查询配置，如果有product配置，让product排前面
            $configFileTmpList = Db::table('config_file_tmp')->whereIn("id", array_values($params['ids']))->select()->toArray();
            $configFileTmpListV2 = [];
            $haveProductConfig = false;
            foreach ($configFileTmpList as $configFileTmp) {
                if ($configFileTmp['config_name'] == "product.csv") {
                    $configFileTmpListV2[] = $configFileTmp;
                    $haveProductConfig = true;
                    break;
                }
            }
            foreach ($configFileTmpList as $configFileTmp) {
                if ($configFileTmp['config_name'] != "product.csv") {
                    $configFileTmpListV2[] = $configFileTmp;
                }
            }
            // 如果没有product配置，则查询数据库
            $configProductMap = [];
            if (!$haveProductConfig) {
                $productModel = new Product();
                $productList = $productModel->queryList([], [], [], [], [], "", $field = "*", $order = "");
                $configProductMap = array_column($productList, null, 'id');
            }

            // 查询
            $createHistoryData = [];
            $configFileList = [];
            foreach ($configFileTmpListV2 as $configFileTmp) {
                // 更新或创建：线上配置
                $onlineData = Db::table('config_file_online')->where(['config_name' => $configFileTmp['config_name']])->select()->toArray();
                if (count($onlineData) == 0) {
                    $createOnlineData = [];
                    $createOnlineData["manager_id"] = $configFileTmp['manager_id'];
                    $createOnlineData["manager_name"] = $configFileTmp['manager_name'];
                    $createOnlineData["config_name"] = $configFileTmp['config_name'];
                    $createOnlineData["config_file"] = $configFileTmp['config_file'];
                    Db::table('config_file_online')->insert($createOnlineData);
                } else {
                    $updateData = [];
                    $updateData["manager_id"] = $configFileTmp['manager_id'];
                    $updateData["manager_name"] = $configFileTmp['manager_name'];
                    $updateData["config_file"] = $configFileTmp['config_file'];
                    Db::table('config_file_online')->where(['config_name' => $configFileTmp['config_name']])->update($updateData);
                }

                // 删除临时记录
                Db::table('config_file_tmp')->where(['config_name' => $configFileTmp['config_name']])->delete();

                // 创建历史记录
                $createHistoryData["manager_id"] = $configFileTmp['manager_id'];
                $createHistoryData["manager_name"] = $configFileTmp['manager_name'];
                $configFileList[] = $configFileTmp['config_file'];

                // 发布配置：Product
                if ($configFileTmp['config_name'] == "product.csv") {
                    $configProductMap = $this->importProduct($configFileTmp['config_file']);
                }
                // 发布配置：Box-RTP
                if ($configFileTmp['config_name'] == "box_rtp.csv") {
                    $this->importBoxRtp($configFileTmp['config_file'], "box_rtp");
                }
                // 发布配置：Forge-RTP
                if ($configFileTmp['config_name'] == "forge_rtp.csv") {
                    $this->importForgeRtp($configFileTmp['config_file'], "forge_rtp");
                }
                // 发布配置：Box
                if ($configFileTmp['config_name'] == "box.csv") {
                    $this->importBox($configFileTmp['config_file'], $configProductMap);
                }
                // 发布配置：Forge
                if ($configFileTmp['config_name'] == "forge.csv") {
                    $this->importForge($configFileTmp['config_file'], $configProductMap);
                }
            }

            // 创建历史记录
            $createHistoryData["config_file"] = implode("|", $configFileList);
            Db::table('config_file_history')->insert($createHistoryData);

            // 如果一切正常，提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 发生异常时回滚事务
            Log::error("[Release Config Error] error:" . $e->getMessage());
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('发布成功');
    }

    /**
     * 批量删除
     * @auth true
     */
    public function remove()
    {
        try {
            $params = $this->request->post();
            $configFileTmp = new ConfigFileTmp();
            $configFileTmp->batchDeleteInfo([], ["field" => "id", "data" => array_values($params['ids'])]);
        } catch (\Exception $e) {
            $this->error('删除失败');
        }

        $this->success('删除成功');
    }

    /**
     * @throws \Exception
     */
    public function importBoxRtp(string $csvFile, string $tableName = "box_rtp")
    {
        //表格字段对应
        $cellName = [
            'id' => 'id',
            'user_value_5day' => 'user_value_5day',
            'low' => 'low',
            'mid' => 'mid',
            'high' => 'high',
            'rtp1' => 'rtp1',
            'rtp2' => 'rtp2',
            'rtp3' => 'rtp3',
            'rtp4' => 'rtp4',
            'k_ban' => 'k_ban',
            'corr_value' => 'corr_value',
            'corr_rtp' => 'corr_rtp',
        ];
        $cellNameMap = [];
        $batchData = [];

        // 读取csv文件
        if (($handle = fopen($csvFile, 'r')) !== FALSE) {
            // 逐行读取CSV文件
            $k = 0;
            while (($sheetData = fgetcsv($handle, 100000, ",")) !== FALSE) {
                if ($k == 0) {
                    foreach ($sheetData as $sheetDataIndex => $sheetDataValue) {
                        CommonLogic::EncodeContentUtf8($sheetDataValue);
                        if (!array_key_exists($sheetDataValue, $cellName)) {
                            throw new  \Exception("csv格式错误");
                        } else {
                            $cellNameMap[$sheetDataIndex] = $cellName[$sheetDataValue];
                        }
                    }
                    $k = 1;
                    continue;
                }

                // 批量写入数据
                $batchDataItem = [];
                foreach ($sheetData as $sheetDataIndex => $sheetDataValue) {
                    CommonLogic::EncodeContentUtf8($sheetDataValue);
                    $field = $cellNameMap[$sheetDataIndex];
                    if (($field == 'Kban') && (!is_numeric($sheetDataValue) || $sheetDataValue < 0 || $sheetDataValue > 1)) {
                        throw new  \Exception($field . ":格式错误");
                    }
                    $batchDataItem[$field] = $sheetDataValue;
                }
                $batchData[] = $batchDataItem;
            }

            // 关闭文件
            fclose($handle);
        } else {
            throw new  \Exception("无法打开文件");
        }

        // 删除
        Db::table($tableName)->delete(true);

        // 写入
        Db::table($tableName)->insertAll($batchData);
    }

    /**
     * @throws \Exception
     */
    public function importForgeRtp(string $csvFile, string $tableName = "forge_rtp")
    {
        //表格字段对应
        $cellName = [
            'id' => 'id',
            'user_value_5day' => 'user_value_5day',
            'low' => 'low',
            'mid' => 'mid',
            'high' => 'high',
            'rtp1' => 'rtp1',
            'rtp2' => 'rtp2',
            'rtp3' => 'rtp3',
            'rtp4' => 'rtp4',
            'k_ban' => 'k_ban',
            'corr_value' => 'corr_value',
            'corr_rtp' => 'corr_rtp',
        ];
        $cellNameMap = [];
        $batchData = [];

        // 读取csv文件
        if (($handle = fopen($csvFile, 'r')) !== FALSE) {
            // 逐行读取CSV文件
            $k = 0;
            while (($sheetData = fgetcsv($handle, 100000, ",")) !== FALSE) {
                if ($k == 0) {
                    foreach ($sheetData as $sheetDataIndex => $sheetDataValue) {
                        CommonLogic::EncodeContentUtf8($sheetDataValue);
                        if (!array_key_exists($sheetDataValue, $cellName)) {
                            throw new  \Exception("csv格式错误");
                        } else {
                            $cellNameMap[$sheetDataIndex] = $cellName[$sheetDataValue];
                        }
                    }
                    $k = 1;
                    continue;
                }

                // 批量写入数据
                $batchDataItem = [];
                foreach ($sheetData as $sheetDataIndex => $sheetDataValue) {
                    CommonLogic::EncodeContentUtf8($sheetDataValue);
                    $field = $cellNameMap[$sheetDataIndex];
                    if (($field == 'Kban') && (!is_numeric($sheetDataValue) || $sheetDataValue < 0 || $sheetDataValue > 1)) {
                        throw new  \Exception($field . ":格式错误");
                    }
                    $batchDataItem[$field] = $sheetDataValue;
                }
                $batchData[] = $batchDataItem;
            }

            // 关闭文件
            fclose($handle);
        } else {
            throw new  \Exception("无法打开文件");
        }

        // 删除
        Db::table($tableName)->delete(true);

        // 写入
        Db::table($tableName)->insertAll($batchData);
    }

    /**
     * @throws  \Exception
     */
    public function importProduct(string $csvFile, $tableName = "product", bool $isInsertProduct = true): array
    {
        //表格字段对应
        $cellName = [
            'id' => 'id',
            '品牌' => 'brand',
            '名称' => 'name',
            '描述' => 'description',
            '图片' => 'image',
            '价格' => 'amount',
        ];
        $cellNameMap = [];
        $batchData = [];

        // 读取csv文件
        if (($handle = fopen($csvFile, 'r')) !== FALSE) {
            // 逐行读取CSV文件
            $k = 0;
            while (($sheetData = fgetcsv($handle, 100000, ",")) !== FALSE) {
                if ($k == 0) {
                    foreach ($sheetData as $sheetDataIndex => $sheetDataValue) {
                        CommonLogic::EncodeContentUtf8($sheetDataValue);
                        if (!array_key_exists($sheetDataValue, $cellName)) {
                            throw new  \Exception("csv格式错误");
                        } else {
                            $cellNameMap[$sheetDataIndex] = $cellName[$sheetDataValue];;
                        }
                    }
                    $k = 1;
                    continue;
                }

                // 批量写入数据
                $batchDataItem = [];
                foreach ($sheetData as $sheetDataIndex => $sheetDataValue) {
                    CommonLogic::EncodeContentUtf8($sheetDataValue);
                    $field = $cellNameMap[$sheetDataIndex];

                    // 如果是非测试，那么需要检查
                    if ($tableName == "product") {
                        if (($field == 'name') && ($sheetDataValue == "")) {
                            throw new  \Exception($field . ":格式错误");
                        }
                        if (($field == 'image')) {
                            $imageArr = explode(".", $sheetDataValue);
                            if (count($imageArr) != 2) {
                                throw new  \Exception($field . ":格式错误");
                            }
                            if (!CommonLogic::CheckImage($imageArr[1])) {
                                throw new  \Exception($field . ":格式错误");
                            }
                        }
                        if (($field == 'k_ban') && (!is_numeric($sheetDataValue) || $sheetDataValue < 0 || $sheetDataValue > 1)) {
                            throw new  \Exception($field . ":格式错误");
                        }
                    }

                    $batchDataItem[$field] = $sheetDataValue;
                }
                $batchData[] = $batchDataItem;
            }

            // 关闭文件
            fclose($handle);
        } else {
            throw new  \Exception("无法打开文件");
        }

        // 需要写入数据
        if ($isInsertProduct) {
            // 删除
            Db::table($tableName)->delete(true);

            // 写入
            Db::table($tableName)->insertAll($batchData);
        }

        $configProductMap = [];
        foreach ($batchData as $batchDataItem) {
            $configProductMap[$batchDataItem['id']] = $batchDataItem;
        }
        return $configProductMap;
    }

    /**
     * @throws  \Exception
     */
    public function importBox(string $csvFile, array $configProductMap, string $tableName = "box")
    {
        //表格字段对应
        $cellName = [
            'id' => 'id',
            '名称' => 'name',
            '描述' => 'description',
            '标签' => 'tags',
            '图片' => 'image',
            '是否热门(0否,1是)' => 'is_hot',
            'spin金额' => 'amount',
            '展示产品' => 'show_products',
            'RTP1' => 'RTP1',
            'RTP2' => 'RTP2',
            'RTP3' => 'RTP3',
            'RTP4' => 'RTP4',
            'RTP5' => 'RTP5',
            '假滚权重' => 'scroll_product_weight',
            '假滚序列' => 'scroll_product_serial',
        ];
        $cellNameMap = [];
        $batchData = [];

        // 读取csv文件
        if (($handle = fopen($csvFile, 'r')) !== FALSE) {
            // 逐行读取CSV文件
            $k = 0;
            while (($sheetData = fgetcsv($handle, 10000000, ",")) !== FALSE) {
                if ($k == 0) {
                    foreach ($sheetData as $sheetDataIndex => $sheetDataValue) {
                        CommonLogic::EncodeContentUtf8($sheetDataValue);
                        if (!array_key_exists($sheetDataValue, $cellName)) {
                            throw new  \Exception("csv格式错误");
                        } else {
                            $cellNameMap[$sheetDataIndex] = $cellName[$sheetDataValue];
                        }
                    }
                    $k = 1;
                    continue;
                }

                $dataItem = [];
                foreach ($sheetData as $sheetDataIndex => $sheetDataValue) {
                    CommonLogic::EncodeContentUtf8($sheetDataValue);
                    $dataItem[$cellNameMap[$sheetDataIndex]] = $sheetDataValue;
                }

                error_log(var_export("====", true) . "\n", 3, "/tmp/qp.log");
                if ($tableName == "box") {
                    // 非测试，需要校验数据
                    $batchData[] = $this->checkBoxData($dataItem, $configProductMap);
                } else {
                    // RTP格式校验
                    $dbRtpArr = [];
                    foreach ($dataItem as $key => $value) {
                        if ($key == "RTP1" || $key == "RTP2" || $key == "RTP3" || $key == "RTP4" || $key == "RTP5") {
                            // 判断最后一个字符是否为分号
                            if (substr($value, -1) === ';') {
                                // 如果是分号，去掉它
                                $value = substr($value, 0, -1);
                            }

                            // 解析第一层：用户价值
                            $valueArr = explode("==", $value);
                            if (count($valueArr) != 2) {
                                throw new  \Exception($key . ":格式错误！");
                            }
                            $dbRtpArr[$valueArr[0]] = $valueArr[1];

                            // 解析第二层
                            $rtpProductIds = [];
                            $valueList = explode(";", $valueArr[1]);
                            foreach ($valueList as $valueItem) {
                                $valueItemArr = explode("|", $valueItem);
                                if (count($valueItemArr) != 3) {
                                    throw new  \Exception($key . ":格式错误！");
                                }
                                if ($valueItemArr[2] < 0) {
                                    throw new  \Exception($key . ":格式错误！");
                                }
                                $rtpProductIds[] = $valueItemArr[0];
                            }
                            $rtpProductIdArr[] = $rtpProductIds;
                            foreach ($rtpProductIds as $productId) {
                                if (!isset($configProductMap[$productId])) {
                                    throw new  \Exception($key . ":未查询到商品信息！");
                                }
                            }
                            unset($dataItem[$key]);
                        }
                    }
                    $dataItem['rtp'] = json_encode($dbRtpArr);
                    $batchData[] = $dataItem;
                }
            }

            // 关闭文件
            fclose($handle);
        } else {
            throw new \Exception("无法打开文件");
        }

        // 删除
        Db::table($tableName)->delete(true);

        // 写入
        Db::table($tableName)->insertAll($batchData);
    }

    /**
     * @throws  \Exception
     */
    public function checkBoxData(array $dataItem, array $configProductMap)
    {
        if ($dataItem["id"] == "" || !is_numeric($dataItem["id"]) || $dataItem["id"] < 0) {
            throw new  \Exception("名称错误");
        }
        if ($dataItem["name"] == "") {
            throw new  \Exception("名称错误");
        }
        if ($dataItem["description"] == "") {
            throw new  \Exception("描述错误");
        }
        if ($dataItem["tags"] == "") {
            throw new  \Exception("标签不能为空");
        }
        if ($dataItem["image"] == "") {
            $imageArr = explode(".", $dataItem["image"]);
            if (count($imageArr) != 2) {
                throw new  \Exception("头像格式错误");
            }
            if (!CommonLogic::CheckImage($imageArr[1])) {
                throw new  \Exception("头像格式错误");
            }
            throw new  \Exception("盒子图片错误");
        }
        if ($dataItem["amount"] == "" || $dataItem["amount"] < 0) {
            throw new  \Exception("开盒金额错误");
        }
        if ($dataItem["show_products"] == "") {
            throw new  \Exception("展示商品格式错误");
        }
        if ($dataItem["RTP1"] == "") {
            throw new  \Exception("RTP1格式错误");
        }
        if ($dataItem["RTP2"] == "") {
            throw new  \Exception("RTP2格式错误");
        }
        if ($dataItem["RTP3"] == "") {
            throw new  \Exception("RTP3格式错误");
        }
        if ($dataItem["RTP4"] == "") {
            throw new  \Exception("RTP4格式错误");
        }
        if ($dataItem["RTP5"] == "") {
            throw new  \Exception("RTP5格式错误");
        }
        if ($dataItem["RTP5"] == "") {
            throw new  \Exception("RTP5格式错误");
        }
        if ($dataItem["scroll_product_weight"] == "") {
            throw new  \Exception("假滚权重格式错误");
        }
        if ($dataItem["scroll_product_serial"] == "") {
            throw new  \Exception("假滚序列格式错误");
        }
        $productModel = new Product();

        // 展示商品校验
        if (substr($dataItem['show_products'], -1) === ';') {
            $dataItem['show_products'] = substr($dataItem['show_products'], 0, -1);
        }
        $showProductIds = [];
        $showProductsList = explode(";", $dataItem["show_products"]);
        foreach ($showProductsList as $showProductsItem) {
            $showProductsItemArr = explode("|", $showProductsItem);
            if (count($showProductsItemArr) != 3) {
                throw new  \Exception("展示商品格式错误");
            }
            if ($showProductsItemArr[2] > 1 || $showProductsItemArr[2] < 0) {
                throw new  \Exception("展示商品格式错误");
            }
            $showProductIds[] = $showProductsItemArr[0];
        }
        $lessThanSpinAmountCount = 0;
        foreach ($showProductIds as $productId) {
            if (!isset($configProductMap[$productId])) {
                throw new  \Exception("展示商品，未查到信息. productId:" . $productId);
            }
            if ($configProductMap[$productId]["amount"] < $dataItem["amount"]) {
                $lessThanSpinAmountCount++;
            }
        }
        if ($lessThanSpinAmountCount == 0) {
            throw new  \Exception("没有小于Spin金额的产品！");
        }

        // 判断最后一个字符是否为分号
        if (substr($dataItem['scroll_product_weight'], -1) === ';') {
            $dataItem['scroll_product_weight'] = substr($dataItem['scroll_product_weight'], 0, -1);
        }
        if (substr($dataItem['scroll_product_serial'], -1) === ';') {
            $dataItem['scroll_product_serial'] = substr($dataItem['scroll_product_serial'], 0, -1);
        }
        // 滚动商品校验
        $scrollProductsWeightIds = [];
        $scrollProductsList = explode(";", $dataItem['scroll_product_weight']);
        foreach ($scrollProductsList as $scrollProductsItem) {
            $scrollProductsItemArr = explode("|", $scrollProductsItem);
            if (count($scrollProductsItemArr) != 3) {
                throw new  \Exception("滚动权重格式错误！");
            }
            if (!isset($configProductMap[$scrollProductsItemArr[0]])) {
                throw new  \Exception("滚动权重商品，未查到信息！");
            }
            $scrollProductsWeightIds[] = $scrollProductsItemArr[0];
        }
        $scrollProductsSerialIds = [];
        $scrollProductsList = explode(";", $dataItem['scroll_product_serial']);
        foreach ($scrollProductsList as $scrollProductsItem) {
            $scrollProductsItemArr = explode("|", $scrollProductsItem);
            if (count($scrollProductsItemArr) != 2) {
                throw new  \Exception("滚动序列格式错误！");
            }
            if (!isset($configProductMap[$scrollProductsItemArr[0]])) {
                throw new  \Exception("滚动序列格商品，未查到信息！");
            }
            $scrollProductsSerialIds[] = $scrollProductsItemArr[0];
        }


        // 判断商品是否完全一样
        if (!empty(array_diff($showProductIds, $scrollProductsWeightIds)) || !empty(array_diff($scrollProductsWeightIds, $showProductIds))) {
            throw new  \Exception("展示商品 和 假滚权重。商品ID不是完全一样的:id:".$dataItem['id']);
        }
        if (!empty(array_diff($scrollProductsSerialIds, $showProductIds)) || !empty(array_diff($scrollProductsSerialIds, $scrollProductsWeightIds))) {
            throw new  \Exception("假滚序列里面的商品，存在不属于展示商品的:id:".$dataItem['id']);
        }

        // RTP格式校验
        $rtpProductIdArr = [];
        $dbRtpArr = [];
        foreach ($dataItem as $key => $value) {
            if ($key == "RTP1" || $key == "RTP2" || $key == "RTP3" || $key == "RTP4" || $key == "RTP5") {
                // 判断最后一个字符是否为分号
                if (substr($value, -1) === ';') {
                    // 如果是分号，去掉它
                    $value = substr($value, 0, -1);
                }

                // 解析第一层：用户价值
                $valueArr = explode("==", $value);
                if (count($valueArr) != 2) {
                    throw new  \Exception($key . ":格式错误！");
                }
                $dbRtpArr[$valueArr[0]] = $valueArr[1];

                // 解析第二层
                $rtpProductIds = [];
                $valueList = explode(";", $valueArr[1]);
                foreach ($valueList as $valueItem) {
                    $valueItemArr = explode("|", $valueItem);
                    if (count($valueItemArr) != 3) {
                        throw new  \Exception($key . ":格式错误！");
                    }
                    if ($valueItemArr[2] < 0) {
                        throw new  \Exception($key . ":格式错误！");
                    }
                    $rtpProductIds[] = $valueItemArr[0];
                }
                $rtpProductIdArr[] = $rtpProductIds;
                foreach ($rtpProductIds as $productId) {
                    if (!isset($configProductMap[$productId])) {
                        throw new  \Exception($key . ":未查询到商品信息！");
                    }
                }
                unset($dataItem[$key]);
            }
        }

        $productIdsStr = "";
        $showProductIds = array_unique($showProductIds);
        foreach ($showProductIds as $productId) {
            $productIdsStr .= "[" . $productId . "]";
        }
        $dataItem['product_ids'] = $productIdsStr;
        $dataItem['rtp'] = json_encode($dbRtpArr);

        return $dataItem;
    }

    /**
     * @throws  \Exception
     */
    public function importForge(string $csvFile, array $configProductMap, string $tableName = "forge")
    {
        //表格字段对应
        $cellName = [
            'id' => 'id',
            '商品ID' => 'product_id',
            '是否热门(0否,1是)' => 'is_hot',
            '头像' => 'head_image',
            '默认spin金额' => 'default_spin_amount',
            '默认中奖概率' => 'forge_probability',
            '最低概率' => 'min_probability',
            '最高概率' => 'max_probability',
            'rtp_base' => 'rtp_base',
            'rtp_corr' => 'rtp_corr',
            'corr_value' => 'corr_value',
            'k_ban' => 'k_ban',
        ];
        $cellNameMap = [];
        $batchData = [];

        // 读取csv文件
        if (($handle = fopen($csvFile, 'r')) !== FALSE) {
            // 逐行读取CSV文件
            $k = 0;
            while (($sheetData = fgetcsv($handle, 100000, ",")) !== FALSE) {
                if ($k == 0) {
                    foreach ($sheetData as $sheetDataIndex => $sheetDataValue) {
                        CommonLogic::EncodeContentUtf8($sheetDataValue);
                        if (!array_key_exists($sheetDataValue, $cellName)) {
                            throw new  \Exception("csv格式错误");
                        } else {
                            $cellNameMap[$sheetDataIndex] = $cellName[$sheetDataValue];
                        }
                    }
                    $k = 1;
                    continue;
                }

                $dataItem = [];
                foreach ($sheetData as $sheetDataIndex => $sheetDataValue) {
                    CommonLogic::EncodeContentUtf8($sheetDataValue);
                    $dataItem[$cellNameMap[$sheetDataIndex]] = $sheetDataValue;
                }
                $batchData[] = $this->checkForgeData($dataItem, $configProductMap);
            }

            // 关闭文件
            fclose($handle);
        } else {
            throw new \Exception("无法打开文件");
        }

        // 删除
        Db::table($tableName)->delete(true);

        // 写入
        Db::table($tableName)->insertAll($batchData);
    }

    /**
     * @throws  \Exception
     */
    public function checkForgeData(array $dataItem, array $configProductMap)
    {
        if ($dataItem["product_id"] == "") {
            throw new  \Exception("商品ID错误！");
        }
        if ($dataItem["forge_probability"] == "" || $dataItem['forge_probability'] <= 0 || $dataItem['forge_probability'] >= 1) {
            throw new  \Exception("打折概率错误！");
        }
        if ($dataItem["min_probability"] == "" || $dataItem['min_probability'] <= 0 || $dataItem['min_probability'] >= 1) {
            throw new  \Exception("最小概率错误！");
        }
        if ($dataItem["max_probability"] == "" || $dataItem['max_probability'] <= 0 || $dataItem['max_probability'] >= 1) {
            throw new  \Exception("最大概率错误！");
        }
        if ($dataItem["default_spin_amount"] == "") {
            throw new  \Exception("默认Spin金额错误！");
        }
        if ($dataItem["rtp_base"] == "" || $dataItem['rtp_base'] <= 0 || $dataItem['rtp_base'] >= 100) {
            throw new  \Exception("rtp_base错误！");
        }
        if ($dataItem["rtp_corr"] == "" || $dataItem['rtp_corr'] <= 0 || $dataItem['rtp_corr'] >= 100) {
            throw new  \Exception("rtp_corr错误！");
        }
        if ($dataItem["corr_value"] == "" || $dataItem['corr_value'] <= 0) {
            throw new  \Exception("corr_value错误！");
        }
        if ($dataItem["k_ban"] == "" || $dataItem['k_ban'] <= 0 || $dataItem['k_ban'] >= 1) {
            throw new  \Exception("k_ban错误！");
        }
        if ($dataItem["head_image"] != "") {
            $imageArr = explode(".", $dataItem["head_image"]);
            if (count($imageArr) != 2) {
                throw new  \Exception("头像格式错误");
            }
            if (!CommonLogic::CheckImage($imageArr[1])) {
                throw new  \Exception("头像格式错误");
            }
        }

        // 展示商品校验
        if (!isset($configProductMap[$dataItem["product_id"]])) {
            throw new  \Exception("未查到商品信息，productId:" . $dataItem["product_id"]);
        }
        if ($dataItem['default_spin_amount'] <= 0 || $dataItem['default_spin_amount'] >= $configProductMap[$dataItem["product_id"]]["amount"]) {
            throw new  \Exception("id:" . $dataItem['id'] . ":默认Spin金额错误！");
        }

        return $dataItem;
    }
}